package algorithm.sort;

import java.util.Arrays;

/**
 * @ Description：插入排序
 */
public class _03InsertSort implements SortAlgrithm {

    public static void main(String[] args) {
        Integer[] arr = SortUtils.getRandomIntArr(10, 100);
        System.out.println(Arrays.toString(arr));
        new _03InsertSort().sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    @Override
    public <T extends Comparable<T>> T[] sort(T[] unsorted) {
        int n = unsorted.length;
        for (int i = 1; i < n; i++) {
            T insertValue = unsorted[i];
            int j;
            for (j = i - 1; j >= 0 && (insertValue.compareTo(unsorted[j]) < 0); j--) {
                unsorted[j + 1] = unsorted[j];
            }
            if (j != i - 1) {
                unsorted[j + 1] = insertValue;
            }
        }
        return unsorted;
    }
}
